﻿namespace UnitTest.Dxp.Orm

open System
open Microsoft.VisualStudio.TestTools.UnitTesting
open Lib.Dxp.Orm
open Lib.Dxp.Orm.DataValueInit

type User internal () = 
    inherit OneTable()
    static member ctor with get() = let x = User() in x.init(); x
    member val Name     = varchar (50)      with get
    member val Comment  = dyn [1..3]        with get
    member val eMail    = dyn [1.3; 2.7]    with get
    member val Phone    = dyn ""            with get



type UserXXX internal () = 
    inherit User()
    static member ctor with get() = let x = UserXXX() in x.init(); x
    member val Like     = dyn ""    with get



[<TestClass>]
type UnitTest_DxpOneTable() = 

    [<TestMethod>]
    member x.t_1 () = 
        let u = UserXXX.ctor
        Assert.AreEqual(Unchecked.defaultof<int>, u.Id.Value)
        Assert.AreEqual(NonInitialized, u.Id.Status)
        Assert.AreEqual(NonInitialized, u.Comment.Status)

    [<TestMethod>]
    member x.t_2 () = 
        let u = UserXXX.ctor
        u.Id.Value <- 11
        Assert.AreEqual(11, u.Id.Value)
        Assert.AreEqual(Updated, u.Id.Status)

    [<TestMethod>]
    member x.t_3 () = 
        let u = UserXXX.ctor
        Assert.AreEqual(sprintf "%A" (Array.sort [|"Like"; "Name"; "Comment"; "eMail"; "Phone"; "Id"|]), 
                        sprintf "%A" (Array.sort u._MetaFields))
        Assert.AreEqual("UserXXX", u._MetaName)
        Assert.AreEqual("Id", u.Id.FieldName)
        Assert.AreEqual("Comment", u.Comment.FieldName)


    [<TestMethod>]
    member x.t_4 () = 
        let u = UserXXX.ctor
        u.Id.Value <- 5
        u.Comment.Value <- [5..7]
        let s = u.save_DynamicAsJson(u)

        let o = UserXXX.ctor
        o.load_DynamicFromJson<UserXXX>(s)
        Assert.AreEqual(0, o.Id.Value)              // o.Id is not dynaic and cannot be serialized
        Assert.AreEqual([5..7], o.Comment.Value)
        Assert.AreEqual([1.3; 2.7], o.eMail.Value)  // [1.3; 2.7] = predefinet value in constructor
        Assert.AreEqual(Loaded, o.eMail.Status)    // but dynamic fields in OneTable always serializable


        u.eMail.Value <- [1.0;2.0;3.5;5.0]
        let s = u.save_DynamicAsJson(u)
        let o = UserXXX.ctor
        o.load_DynamicFromJson<UserXXX>(s)
        Assert.AreEqual([1.0;2.0;3.5;5.0], o.eMail.Value)  // [1.3; 2.7] = predefinet value in constructor
        Assert.AreEqual(Loaded, o.eMail.Status)